import React, {Component} from 'react'
import {Modal, Spin} from 'antd'
import DPlayer from 'dplayer'
import 'dplayer/dist/DPlayer.min.css'
import 'moment/locale/zh-cn'
import {sleep} from '../common/js/utils'
import propTypes from 'prop-types'

class MiniPlayer extends Component {

  state = {
    visible: false,
    loading: true
  }

  handleClose = () => {
    this.player && this.player.pause && this.player.pause()
  }

  handleCancel = () => {
    this.setState({
      visible: false
    })
  }

  componentWillMount() {
    this.props.onRef && this.props.onRef(this)
  }

  showModal = (item) => {
    this.setState({
      visible: true
    }, async () => {
      if (this.player) {
        if (this.player.video.currentSrc !== item.video) {
          this.player.switchVideo({
            url: item.video,
            autoplay: true,
            pic: item.cover,
            type: 'auto'
          })
        }
        this.player.play()
      } else {
        await sleep(1000)
        const dom = this.refs.video
        this.setState({
          loading: false
        })
        this.player = new DPlayer({
          container: dom,
          screenshot: true,
          autoplay: true,
          video: {
            url: item.video,
            pic: item.cover,
            thumbnails: item.cover
          }
        })
      }
    })
  }

  render() {
    return (
      <Modal
        footer={null}
        afterClose={this.handleClose}
        visible={this.state.visible}
        onCancel={this.handleCancel}
        centered
        bodyStyle={{
          padding: 0
        }}
      >
        <Spin size="large" spinning={this.state.loading}>
          <div ref="video" style={{
            minHeight: 200,
          }} />
        </Spin>
      </Modal>
    )
  }
}

MiniPlayer.propTypes = {
  onRef: propTypes.func
}

export default MiniPlayer
